package com.tensquare.article.service.impl;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.repository.CommentRepository;
import com.tensquare.article.service.CommentService;
import com.tensquare.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service("commentService")
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Comment findById(String id) {
        Optional<Comment> optional = commentRepository.findById(id);
        return optional.orElse(null);
    }

    @Override
    public List<Comment> findAll() {
        return commentRepository.findAllByIsdelete(0);
    }

    @Override
    public void save(Comment comment) {
        //初始化评论
        comment.set_id(String.valueOf(idWorker.nextId()));
        comment.setIsdelete(0);
        comment.setThumbup(0);
        comment.setPublishdate(new Date());

        commentRepository.insert(comment);
    }

    @Override
    public void update(Comment comment) {
        commentRepository.save(comment);
    }

    @Override
    public void deleteById(String id) {
        Optional<Comment> optional = commentRepository.findById(id);
        if (optional.isPresent()) {
            Comment comment = optional.get();
            comment.setIsdelete(1);
            commentRepository.save(comment);
        }
    }

    @Override
    public List<Comment> findByArticleId(String article) {
        return commentRepository.findAllByArticleidAndIsdelete(article, 0);
    }

    @Override
    public void thumbUp(String id,String userId) {
        //操作两次数据库效率更低
//        test1(id);

//        Query query = new Query(Criteria.where("_id").is(id).and("userid").is(userId));
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, update, Comment.class);
    }

    private void test1(String id) {
        Optional<Comment> optional = commentRepository.findById(id);
        if (optional.isPresent()) {
            Comment comment = optional.get();
            //修改点赞数
            comment.setThumbup(comment.getThumbup() + 1);
            commentRepository.save(comment);
        }
    }
}
